package cqrtplm.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.handle.CountHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.Event;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.SequenceFlow;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskInfo;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@CustomListener(category = "润通",description = "驳回统计节点处理并行节点任务")
public class RTCustomAutoRejectTaskListener implements ExecutionListener {

    public void notify(DelegateExecution execution) {
        try {
            log.info("开始执行监听 ==> 驳回统计节点处理并行节点任务CustomAutoRejectTaskListener");
            FlowElement currentFlowElement = execution.getCurrentFlowElement();
            if(currentFlowElement instanceof Event) {
                List<SequenceFlow> incomingFlows = ((Event) currentFlowElement).getIncomingFlows();
                if(CollUtil.isEmpty(incomingFlows)) {
                    return;
                }
                Set<String> userTaskKeys = new HashSet<>();
                Map<String,String> userTaskKeyAndSequenceFlowIdMap = new HashMap<>();
                //找到连接到驳回统计节点的用户任务id
                for (SequenceFlow flow : incomingFlows) {
                    userTaskKeys.add(flow.getSourceRef());
                    userTaskKeyAndSequenceFlowIdMap.put(flow.getSourceRef(),flow.getId());
                }
                TaskService taskService = SpringUtil.getBean(TaskService.class);
                //查询当前流程实例的任务
                List<Task> list = taskService.createTaskQuery().processInstanceId(execution.getProcessInstanceId())
                        .list();
                if(CollUtil.isEmpty(list)) {
                    return;
                }
                //过滤出并行节点的任务id
                Set<String> needDeleteTaskIdSet = list.stream().filter(
                        task -> userTaskKeys.contains(task.getTaskDefinitionKey())).map(Task::getId).collect(
                        Collectors.toSet());
                Map<String, String> taskIdAndUserTaskKeyMap = list.stream().filter(
                        task -> userTaskKeys.contains(task.getTaskDefinitionKey())).collect(
                        Collectors.toMap(Task::getId, TaskInfo::getTaskDefinitionKey, (k1, k2) -> k2));
                if(CollUtil.isEmpty(needDeleteTaskIdSet)) {
                    return;
                }
                //完成对应任务（不记录日志等信息，按照驳回线直接完成）
                for (String taskId : needDeleteTaskIdSet) {
                    String userTaskKey = taskIdAndUserTaskKeyMap.get(taskId);
                    if(StringUtils.isBlank(userTaskKey)) {
                        continue;
                    }
                    String SequenceFlowId = userTaskKeyAndSequenceFlowIdMap.remove(userTaskKey);
                    if(StringUtils.isBlank(SequenceFlowId)) {
                        continue;
                    }
                    String routerCountKey = CountHandler.getTotalKey(SequenceFlowId);
                    Object obj = taskService.getVariable(taskId, "nrOfInstances");
                    int taskCount = Integer.parseInt(obj.toString());
                    taskService.setVariable(taskId, routerCountKey, taskCount);
                    taskService.setVariable(taskId, "nrOfCompletedInstances", taskCount);
                    taskService.setVariable(taskId, "lastChoiceFlag", SequenceFlowId);
                    taskService.setVariable(taskId, "completeFlag", true);
                    taskService.setVariable(taskId, "requiredFlag", true);
                    taskService.setVariable(taskId, "multiChooseFlag", false);
                    taskService.complete(taskId);
                }
            }
        } catch (Exception e) {
            log.error("监听CustomAutoRejectTaskListener异常：", e);
            throw e;
        }
    }
}